import React, {useEffect, useState} from "react";
import useStateRef from 'react-usestateref'

import Header from "../components/Header";
import Footer from "../components/Footer";

import {Button, Input, notification, Popconfirm, Space, Table, Modal, Spin, Checkbox, Tag} from "antd";
import {fieldGet, paramChange} from "../common/common";
import http from "../request";
import Recycle from "../components/Recycle";

const Auth = () => {
    const pageDefault = {page: 1, pageSize: 10}
    const [authSource, setAuthSource] = useState([])
    const [authColumn] = useState([
        {
            title: '名称',
            dataIndex: 'name',
        }, {
            title: '权限',
            dataIndex: 'ruleList',
            render: e => (
                e.map(auth => <Tag color="geekblue" key={'auth-'+auth.id}>{auth.title}</Tag>)
            )
        }, {
            title: '操作',
            width: 80,
            render: e => (
                <Space size="middle">
                    <img className="u-btn" src='../assets/icon/icon-12.png' alt="" title="编辑" onClick={() => authEdit(e.id)}/>
                    <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={() => authDel(e.id)}>
                        <img className="u-btn" src='../assets/icon/icon-13.png' alt="" title="删除"/>
                    </Popconfirm>
                </Space>
            )
        }
    ])
    const [authPager] = useState(pageDefault)
    const [authSelect, setAuthSelect] = useState([])
    const [authShow, setAuthShow] = useState(!1)
    const [authForm, setAuthForm] = useState({})

    const [mask, setMask] = useState({show: !1, text: ''})

    const [indeterminate, setIndeterminate] = React.useState(!1);
    const [authAll, setAuthAll] = React.useState(!1);
    const [authOptions, setAuthOptions, authOptionsRef] = useStateRef([])
    const [authValue, setAuthValue] = useState([])

    // 回收站-列
    const backColumns = [
        {
            title: '名称',
            dataIndex: 'name',
        }, {
            title: '权限',
            dataIndex: 'ruleList',
            render: e => (
                e.map(auth => <Tag color="geekblue" key={'auth-'+auth.id}>{auth.title}</Tag>)
            )
        }
    ]

    useEffect(() => {
        ruleGet()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
    useEffect(() => {
        authGet()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [authPager])
    useEffect(() => {
        !authShow && authReset()
    }, [authShow])

    return (
        <React.Fragment>
            <Header navCur={5}/>
            <div className="Store page u-m-20 u-p-20">
                <div className="part-title">所属职务权限管理</div>
                <Recycle url='auth' func={authGet} columns={backColumns} className="u-m-t-20" />
                <div className="u-m-t-20">
                    <Table bordered size="small" rowSelection={{
                        selectedRowKeys: authSelect,
                        onChange(e){
                            setAuthSelect(e)
                        }
                    }} onRow={e => ({
                        onDoubleClick: () => {
                            authEdit(e.id)
                        }
                    })} rowKey={e => e.id} dataSource={authSource} columns={authColumn} pagination={false} />
                </div>
                <div className="u-flex u-row-between u-m-t-20">
                    <div>
                        <Button type="primary" size="small" onClick={() => setAuthShow(!0)}>
                            <div className="u-flex">
                                <img src={require('../assets/icon/icon-18.png').default} alt=""/>
                                <span className="u-m-l-5">新增</span>
                            </div>
                        </Button>
                        <Popconfirm title="确定删除？" okText="确定" cancelText="取消" onConfirm={authDel}>
                            <Button className="u-m-l-20" type="primary" size="small" danger>
                                <div className="u-flex">
                                    <img src={require('../assets/icon/icon-19.png').default} alt=""/>
                                    <span className="u-m-l-5">删除</span>
                                </div>
                            </Button>
                        </Popconfirm>
                    </div>
                    {/* <Pagination showQuickJumper current={authPager.page} pageSize={authPager.pageSize} total={authTotal} /> */}
                </div>
            </div>

            <Modal title="权限管理" visible={authShow} onOk={authConfirm} onCancel={() => setAuthShow(!1)}>
                <div className="Modal">
                    { mask.show && <div className="mask">
                        <Spin size="large" tip={mask.text} />
                    </div> }
                    <div className="u-flex u-m-t-20">
                        <div className="label">名称</div>
                        <Input value={authForm.name} onChange={e => paramChange(setAuthForm, authForm, 'name', e.target.value)} placeholder="员工名称" className="u-m-l-10" style={{width: 200}}/>
                    </div>
                    <div className="u-flex u-col-top u-m-t-20">
                        <div className="label">权限</div>
                        <div className="u-m-l-10 u-flex-1">
                            <Checkbox indeterminate={indeterminate} onChange={e => {
                                setAuthValue(e.target.checked ? authOptions.map(e => e.value) : []);
                                setIndeterminate(!1);
                                setAuthAll(e.target.checked);
                            }} checked={authAll}>全选</Checkbox>
                            <br/>
                            <Checkbox.Group options={authOptions} value={authValue} onChange={list => {
                                setAuthValue(list);
                                setIndeterminate(!!list.length && list.length < authOptions.length);
                                setAuthAll(list.length === authOptions.length);
                            }}/>
                        </div>
                    </div>
                </div>
            </Modal>

            <Footer/>
        </React.Fragment>
    )

    function authGet(){
        http('auth.list', {
            ...fieldGet(
                authPager.page,
                authPager.pageSize
            )
        }).then(res => {
            if(res.code === 1){
                setAuthSource(res.data.rows)
            }
        }).catch(err=>console.log(err))
    }
    function authReset(){
        setAuthForm({})
        setIndeterminate(!1)
        setAuthValue([])
        setAuthAll(!1)
    }
    function authConfirm(){
        setMask({show: !0, text: '提交中...'})
        let newForm = {...authForm}
        newForm.rules = authValue.toString()
        let url = authForm?.id ? 'auth.edit' : 'auth.add'
        http(url, {
            row: newForm
        }).then(res => {
            if(res.code === 1){
                notification.success({
                    message: res.msg || '添加成功'
                })
                setAuthShow(!1)
            } else {
                notification.error({
                    message: res.msg || '操作失败，请重试'
                })
            }
            authGet()
            setMask({show: !1, text: ''})
        }).catch(err=>console.log(err))
    }
    function authEdit(ids){
        http('auth.one', {ids}).then(res => {
            if(res.code === 1){
                setAuthForm(res.data)
                let list = res.data.rules ? res.data.rules.split(',') : []
                setAuthValue(list)
                setIndeterminate(!!list.length && list.length < authOptionsRef.current.length);
                setAuthAll(list.length === authOptionsRef.current.length);
                setAuthShow(!0)
            }
        }).catch(err=>console.log(err))
    }
    function authDel(id){
        let ids = id > 0 ? [id] : authSelect
        http('auth.del', {ids}).then(res => {
            if(res.code === 1){
                authGet()
            }
        }).catch(err=>console.log(err))
    }

    function ruleGet(){
        http('rule.all').then(res => {
            if(res.code === 1){
                setAuthOptions(res.data.map(e => ({
                    label: e.title,
                    value: e.id.toString()
                })))
            }
        }).catch(err=>console.log(err))
    }
}

export default Auth